import cv2
import numpy as np
import time
from Homework2 import noise_img

# 读取灰度图像
img = cv2.imread('demo.jpg', cv2.IMREAD_GRAYSCALE)

# 定义sobel算子
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])

# 定义Roberts算子
roberts_x = np.array([[1, 0], [0, -1]])
roberts_y = np.array([[0, 1], [-1, 0]])

# 边缘检测
edge_x = np.zeros_like(img)
edge_y = np.zeros_like(img)
edge_x1 = np.zeros_like(img)
edge_y1 = np.zeros_like(img)

noise_x = np.zeros_like(noise_img)
noise_y = np.zeros_like(noise_img)
noise_x1 = np.zeros_like(noise_img)
noise_y1 = np.zeros_like(noise_img)

sobel_start_time = time.time()
# 对图像进行sobel卷积
for i in range(1, img.shape[0] - 1):
    for j in range(1, img.shape[1] - 1):
        edge_x[i, j] = np.sum(sobel_x * img[i - 1:i + 2, j - 1:j + 2])
        noise_x[i, j] = np.sum(sobel_x * noise_img[i -1:i + 2, j-1:j + 2])
        edge_y[i, j] = np.sum(sobel_y * img[i - 1:i + 2, j - 1:j + 2])
        noise_y[i, j] = np.sum(sobel_x * noise_img[i - 1:i + 2, j - 1:j + 2])

# 计算边缘强度
edge = np.sqrt(np.square(edge_x) + np.square(edge_y))
sobel_end_time = time.time()
noise = np.sqrt(np.square(noise_x) + np.square(noise_y))

roberts_start_time = time.time()
# 对图像进行roberts卷积
for i in range(1, img.shape[0]):
    for j in range(1, img.shape[1]):
        edge_x1[i, j] = np.sum(roberts_x * img[i - 1:i + 1, j - 1:j + 1])
        noise_x1[i, j] = np.sum(roberts_x * noise_img[i - 1:i + 1, j - 1:j + 1])
        edge_y1[i, j] = np.sum(roberts_y * img[i - 1:i + 1, j - 1:j + 1])
        noise_y1[i, j] = np.sum(roberts_y * noise_img[i - 1:i + 1, j - 1:j + 1])


# 计算边缘强度
edge_roberts = np.sqrt(np.square(edge_x1) + np.square(edge_y1))
roberts_end_time = time.time()
noise_roberts = np.sqrt(np.square(noise_x1) + np.square(noise_y1))

sobel_time = sobel_end_time - sobel_start_time
roberts_time = roberts_end_time - roberts_start_time
print("sobel卷积执行的时间为：{:.3f}秒".format(sobel_time))
print("roberts卷积执行的时间为：{:.3f}秒".format(roberts_time))

# 显示结果
cv2.imwrite('demo_noise_img.jpg',noise_img)
cv2.imwrite('demo_edge.jpg',edge.astype(np.uint8))
cv2.imwrite('demo_edge_roberts.jpg',edge_roberts.astype(np.uint8))
cv2.imwrite('demo_noise_roberts.jpg',noise_roberts.astype(np.uint8))


cv2.namedWindow('demo_noise_img',cv2.WINDOW_NORMAL)
cv2.namedWindow('demo_edge', cv2.WINDOW_NORMAL)
cv2.namedWindow('demo_edge_roberts', cv2.WINDOW_NORMAL)
cv2.namedWindow('demo_noise_roberts', cv2.WINDOW_NORMAL)
cv2.imshow('demo_noise_img', noise.astype(np.uint8))
cv2.imshow('demo_edge', edge.astype(np.uint8))
cv2.imshow('demo_edge_roberts', edge_roberts.astype(np.uint8))
cv2.imshow('demo_noise_roberts', noise_roberts.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()



